package com.snow.useviewdemo.util.download;

import android.text.TextUtils;

import com.snow.useviewdemo.util.ThreadCacheTools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhyt
 * Date: 2022/10/8
 * Describe:
 */
public class DownLoadUtils {

    private static DownLoadUtils downloadUtil;
    private OkHttpClient okHttpClient;

    public static DownLoadUtils getInstance() {
        if (downloadUtil == null) {
            downloadUtil = new DownLoadUtils();
        }
        return downloadUtil;
    }

    public DownLoadUtils() {
        createHttpClient();
    }

    private void createHttpClient() {
        okHttpClient = new OkHttpClient();
    }

    public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        if (okHttpClient == null) {
            createHttpClient();
        }
        ThreadCacheTools.newThread(() -> startDownload(url, destFileDir, destFileName, listener));
    }

    /**
     * 必须在子线程中调用
     *
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称，后面记得拼接后缀，否则手机没法识别文件类型
     * @param listener     下载监听
     */
    private void startDownload(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        if (listener == null) {
            return;
        }
        if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
            listener.onDownloadFailed(new Exception("url can not null and must startsWith http"));
            return;
        }
        Request request = new Request.Builder()
                .url(url)
                .tag(url)
                .build();
        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    //储存下载文件的目录
                    File dir = new File(destFileDir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File file = new File(dir, destFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    //下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 取消下载请求
     *
     * @param tag 下载文件的url
     */
    public void cancelOkHttpRequest(Object tag) {
        if (tag == null || okHttpClient == null)
            return;
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : okHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

    public void destroy() {
        okHttpClient = null;
    }
}
